import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Text, View, Swiper, SwiperItem, Block, Image} from '@tarojs/components'
import Skeleton from 'taro-skeleton'
import {http} from "../../utils/http";
import {GetRequest, getTempSellerId, setTempSellerId, vcmonitor} from "../../utils/tools";
import {
  RESOURCE_URL,
  SELECT_CAR_DETAIL,
  TARO_ENV
} from "../../constants/api";
import DetailHeader from './components/detail-header/detail-header';
import OtherBar from "./components/detail-bar/other-bar";
import {user} from "../../utils/user.service";
import {platform} from "../../utils/platform-settting.service";
import './detail.scss'
import {h5Wx} from "../../utils/h5.service";
import {getContent} from "../../utils/handlerPublicCode";

type pageState = {
  info: any
  height: any
  configIndex: any
  showLoading: any
}

export default class Detail extends Component {
  state: pageState = {
    showLoading: true,
    info: '',
    height: 0,
    configIndex: 0
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    vcmonitor(this)
    const params: any = Taro.getCurrentInstance().router.params
    let {uuid = '', scene = ''} = params
    let tempSellerId = getTempSellerId(this)
    let bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    if (scene) {
      platform.scene = 0;
      scene = scene.split('_');
      if (scene[2]) {
        tempSellerId = scene[2]
        setTempSellerId(tempSellerId)
      }
      uuid = scene[3]
      if (platform.info.isSellerPermanentLock) {
        if (!bindSellerId && scene[1]) {
          bindSellerId = scene[1];
        }
      } else {
        if (scene[1]) {
          bindSellerId = scene[1];
        }
      }
    }
    this.uuid = uuid
    user.bindSellerId = bindSellerId
    await Taro.setStorage({
      key: 'bindSellerId',
      data: user.bindSellerId
    })
    const shareParams: any = await user.getSellerParam(tempSellerId)
    if (shareParams) {
      this.shareParams = `${shareParams.sellerId || ''}_${shareParams.bindSellerId || ''}_${shareParams.tempSellerId || ''}_${this.uuid}`
    }
    const isH5 = TARO_ENV === 'h5'
    const info = await http.carGet(SELECT_CAR_DETAIL, {uuid: this.uuid})
    if (!info) {
      this.setState({showLoading: false})
      return false
    }
    if (info.configuration && info.configuration.length > 0) {
      info.configuration = this.sliceArr(info.configuration, 6)
    }
    await Taro.setNavigationBarTitle({title: info.name})
    if (isH5) {
      const shareData = {
        title: info.name,
        link: window.location.origin + '/other/carRental/detail?scene=' + this.shareParams,
        imgUrl: info.photos[0]
      }
      await h5Wx.share(shareData)
    }
    try {
      await Taro.getImageInfo({
        src: info.photos[0] + "?x-oss-process=image/resize,w_750",
        success: (res) => {
          this.setState({height: res.height * 750 / res.width})
        }
      })
    } catch (e) {
    }
    this.setState({info, showLoading: false}, () => {
      if (isH5 && info.notice) {
        setTimeout(() => {
          const images = []
          document.querySelectorAll('#html-description img').forEach((ele, i) => {
            images.push(ele.src)
            ele.addEventListener('click', function () {
              Taro.previewImage({
                urls: images,
                current: ele.src
              })
            }, false)
          })
        }, 2000)
      }
    })
  }

  onShareAppMessage() {
    const {name, photos} = this.state.info
    return {
      title: name,
      path: '/other/carRental/detail?scene=' + this.shareParams,
      imageUrl: photos[0]
    }
  }

  onShareTimeline() {
    const {name, photos} = this.state.info
    return {
      title: name,
      query: 'scene=' + this.shareParams,
      imageUrl: photos[0]
    }
  }

  uuid = ''
  shareParams = ''

  sliceArr(arr, size) {
    const newArr = [];
    for (let x = 0; x < Math.ceil(arr.length / size); x++) {
      const start = x * size;
      const end = start + size;
      newArr.push(arr.slice(start, end));
    }
    return newArr;
  }

  configChange(e) {
    this.setState({configIndex: e.detail.current || 0})
  }

  render() {
    const {info, height, configIndex, showLoading} = this.state;
    return (
      <View className='carRentalDetail'>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='250px'>
          {info && <DetailHeader images={info.photos} height={height} />}
        </Skeleton>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='250px'>
          <Block>
            {info && <View className='configuration-wrapper'>
              <View className={`configuration-info ${TARO_ENV + 'configuration-info'}`}>
                {!!info.name && <View className='car-detail-title'>
                  {info.name}
                </View>}
                <View className='price-box'><Text className='car-symbol'>￥</Text><Text
                  className='car-price'
                >{info.per_price}</Text><Text className='car-unit'>日均</Text></View>
              </View>
              {!!info.array && info.array.length > 0 &&
              <View className='configuration-detail configuration-detail-config'>
                {info.array.map((item, index) =>
                  <View className='configuration-detail-info' key={index}>
                    <View className='configuration-detail-info-top'>{item.key}</View>
                    <View style='height: 6px' />
                    <View className='configuration-detail-info-bottom'>{item.value}</View>
                  </View>
                )}
              </View>}
            </View>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='100px'>
          <Block>
            {!!info.configuration && info.configuration.length > 0 &&
            <View className='configuration--title'>配置信息</View>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='25px'>
          <Block>
            {!!info.configuration && info.configuration.length > 0 &&
            <View className='configuration-wrapper configuration-wrapper-swiper'>
              <View className='configuration-detail configuration-detail-swiper'>
                <Swiper className='swiper-box' autoplay onChange={this.configChange.bind(this)} current={configIndex}>
                  {info.configuration.map((item, i) => {
                      return <SwiperItem className='swiper-box-item' key={i} key={i}>
                        {item.map((items, index) => <View key={index}
                          className='configuration-detail-info configuration-detail-info-swiper'
                        >
                          <View className='configuration-detail-info-swiper-bg'>
                            <View className='configuration-detail-info-top'>{items.key}</View>
                            <View style='height: 6px' />
                            <View className='configuration-detail-info-bottom'>{items.value}</View>
                          </View>
                        </View>)}
                      </SwiperItem>
                    }
                  )}
                </Swiper>
                <View className='indicator-box-car'>
                  {info.configuration.map((_, i) => <View key={i} key={i}
                    className={`indicator-item-car ${i === configIndex && 'active'}`}
                  />)}
                </View>
              </View>
            </View>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='100px'>
          <Block>
            {!!info.notice && <View className='configuration-wrapper' style='padding-top: 10px'>
              <View className='configuration--title configuration--title-intro'>预订须知</View>
              {TARO_ENV === 'weapp' && <View className='reservation-instructions'>
                <parser selectable html={info.notice || ''} />
              </View>}
              {TARO_ENV === 'tt' && <View className='reservation-instructions'>
                <rich-text preview selectable nodes={getContent(info.notice)} />
              </View>}
              {TARO_ENV === 'h5' && <Text selectable className='reservation-instructions'>
                <View id='html-description' dangerouslySetInnerHTML={{__html: info.notice}} />
              </Text>}
            </View>}
          </Block>
        </Skeleton>
        <Skeleton loading={showLoading} title titleWidth='100%' rowHeight='100px'>
          <Block>
            {info && <OtherBar />}
          </Block>
        </Skeleton>
      </View>
    )
  }
}
